<template>
  <div class="search">
    <!-- 头部标题 -->
    <van-search
      @input="think"
      v-model="value"
      background="#3296fa"
      show-action
      placeholder="请输入搜索关键词"
      @search="onSearch"
      @cancel="onCancel"
    />
    <!-- 联想区域 -->
    <van-cell-group v-if="thinkList.length != 0">
      <van-cell title="联想区域" />
      <van-cell
        @click="onSearch(item.oldItem)"
        v-for="(item, index) in thinkList"
        :key="index"
        icon="search"
      >
        <template #title>
          <div v-html="item.newItem"></div>
        </template>
      </van-cell>
    </van-cell-group>
    <!-- 历史区域 -->
    <van-cell-group v-else>
      <van-cell title="历史搜索">
        <template #default><van-icon name="delete" @click="delAll" /></template>
      </van-cell>
      <van-cell @click="onSearch(item)" v-for="(item, index) in historyList" :key="index" :title="item" icon="search">
          <template #default><van-icon name="cross" @click.stop="delhistory(index)"/></template>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { apiThink } from '@/api/search.js'
import { localSet, localGet, localDel } from '@/utils/mylocal.js'
export default {
  data () {
    return {
      value: '',
      // 联想数据保存
      thinkList: [],
      // 定义一个定时器
      timer: null,
      // 搜索历史
      historyList: localGet('history') || []
    }
  },
  methods: {
    // 删除历史记录
    delAll () {
      // 打开一个弹窗
      this.$dialog.confirm({
        title: '标题',
        message: '是否清空历史记录'
      })
        .then(() => {
          // 将historyList清空
          this.historyList = []
          // 将本地数据也清空
          localDel('history')
        })
        .catch(() => {
          // on cancel
          window.console.log('取消')
        })
    },
    // 删除历史数据
    delhistory (index) {
      this.historyList.splice(index, 1)
      // 操作结果保存到本地
      localSet(this.historyList, 'history')
    },
    // 联想
    think (val) {
      if (val.trim().length === 0) {
        this.thinkList = []
        return
      }
      // 解决抖动问题
      clearTimeout(this.timer)
      this.timer = setTimeout(async () => {
        const res = await apiThink(val)
        this.thinkList = res.data.data.options
        // 遍历thinkList 将每个元素中的val(关键词)替换成<span style="color:red">${val}</span>
        this.thinkList = this.thinkList.map(item => {
          return {
            newItem: item.replace(val, `<span style="color:red">${val}</span>`),
            oldItem: item
          }
        })
      }, 700)
    },
    // 点击键盘上的完成按钮时触发
    // val 输入框中的内容
    onSearch (val) {
      console.log(val)
      // 页面间传参新方法(动态路由传参)
      this.$router.push(`/searchResult/${val}`)
      // 保存历史数据
      this.historyList.unshift(val)
      this.historyList = [...new Set(this.historyList)]
      // 保存到本地
      localSet(this.historyList, 'history')
    },
    // 点击取消按钮时触发：会清空输入框
    onCancel () {
      console.log('onCancel')
    }
  }
}
</script>

<style lang="less" scoped>
.search {
  .van-search__action {
    color: #fff;
  }
  .van-search__action:active {
    background-color: #3296fa;
    color: red;
  }
}
</style>
